<template>
  <zz-Dialog
    v-model="open"
    @confirm="handleOk"
    @cancel="handleClose"
    :loading="loading"
    :title="title"
    :align-center="true"
    :size="'large'"
  >
    <el-container class="dialog-template-layout">
      <el-main>
        <zz-Form
          ref="rootForm"
          :rules="ruleValidate"
          :model="model"
          :readOnly="type === 'view'"
        >
          <el-col :span="12">
            <el-form-item label="用户编码" prop="userCode">
              <el-input
                v-model="model.userCode"
                :placeholder="'请输入用户编码'"
                :maxlength="64"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="model.userName"
                :placeholder="'请输入用户名称'"
                :maxlength="64"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select
                v-model="model.sex"
                :placeholder="'请选择性别'"
                @change="changeSex"
                clearable
                transfer
              >
                <el-option
                  v-for="item in sexList"
                  :value="item.sexCode"
                  :key="item.sexId"
                  :label="item.sexName"
                  >{{ item.sexName }}
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDay">
              <el-date-picker
                type="date"
                v-model="model.birthDay"
                :placeholder="'请选择出生日期'"
                transfer
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input
                v-model="model.age"
                :placeholder="'请输入年龄'"
                :maxlength="64"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="telephone">
              <el-input
                v-model="model.telephone"
                :placeholder="'请输入手机号'"
                :maxlength="64"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间" prop="failureTime">
              <el-input
                v-model="model.failureTime"
                :placeholder="'请输入失效时间'"
                :maxlength="64"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="type === 'add' || type === 'view'">
            <el-form-item label="创建时间" prop="createDate">
              <el-date-picker
                type="datetime"
                v-model="model.createDate"
                :placeholder="'请选择创建时间'"
                transfer
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="type === 'edit' || type === 'view'">
            <el-form-item label="更新时间" prop="updateDate">
              <el-date-picker
                type="datetime"
                v-model="model.updateDate"
                :placeholder="'请选择更新时间'"
                transfer
              />
            </el-form-item>
          </el-col>
        </zz-Form>
      </el-main>
    </el-container>
  </zz-Dialog>
</template>

<script setup>
import { computed, getCurrentInstance, ref, watch } from "vue";
const { proxy } = getCurrentInstance();

// props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

// emits
const emit = defineEmits(["update:modelValue", "query"]);

const open = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

watch(
  open,
  (newValue, oldValue) => {
    if (newValue) {
      init();
    }
  },
  { immediate: true }
);

const loading = ref(false);
const title = ref("");
const type = ref("add"); // 表单模式，add新增，edit编辑，view查看

const sexList = ref([]);

// 表单
const rootForm = ref(null);

const model = ref({
  userId: "",
  userCode: "",
  userName: "",
  sex: "",
  age: "",
  telephone: "",
  failureTime: "",
  createDate: null,
  updateDate: null,
});

// 表单校验规则
const ruleValidate = ref({});

// 初始化
const init = async () => {};

// 保存
const handleOk = async () => {
  let valid = await proxy.$refs.rootForm.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  let params = dealParams();
  if (model.value.userId) {
    modify(params);
  } else {
    save(params);
  }
};

const dealParams = () => {
  let params = {
    ...model.value,
  };
  // todo: 处理特殊格式数据
  params["birthDay"] = proxy.$TOOL.format.formatDate(model.value["birthDay"]);
  params["createDate"] = proxy.$TOOL.format.formatDateTime(
    model.value["createDate"]
  );
  params["updateDate"] = proxy.$TOOL.format.formatDateTime(
    model.value["updateDate"]
  );
  return params;
};

// 新增
const save = async (params) => {
  let res = await proxy.$API.authUserManagement.authUser.save.post(params);
  if (res.code === "01") {
    proxy.$message.success("新增成功");
    emit("query");
    handleClose();
    loading.value = false;
  } else {
    console.error("新增失败", res);
    loading.value = false;
  }
};

// 修改
const modify = async (params) => {
  if (!model.value.userId) {
    return;
  }
  params.userId = model.value.userId;
  let res = await proxy.$API.authUserManagement.authUser.modify.post(params);
  if (res.code === "01") {
    proxy.$message.success("修改成功");
    emit("query");
    handleClose();
    loading.value = false;
  } else {
    console.error("修改失败", res);
    loading.value = false;
  }
};

// 更改
const changeSex = (value) => {};

// 关闭
const handleClose = () => {
  open.value = false;
  reset();
};

// 清除数据
const reset = () => {
  proxy.$refs.rootForm.resetFields();
  model.value = {
    userId: "",
    userCode: "",
    userName: "",
    sex: "",
    age: "",
    telephone: "",
    failureTime: "",
    createDate: null,
    updateDate: null,
  };
};

defineExpose({ title, type, model });
</script>
